package com.intco.ait.quotation.api.starter.advice;

import java.text.SimpleDateFormat;
import java.util.ArrayDeque;
import java.util.Date;
import java.util.Deque;

public class ThreadLogContext {

    private static final ThreadLocal<Deque<String>> THREAD_LOG_ID_STACK = ThreadLocal.withInitial(ArrayDeque::new);

    public static void setThreadLogId() {
        long threadId = Thread.currentThread().getId();
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String logId = "thread-" + threadId + "-" + timestamp;
        THREAD_LOG_ID_STACK.get().push(logId);
    }

    public static String getThreadLogId() {
        Deque<String> stack = THREAD_LOG_ID_STACK.get();
        return stack.isEmpty() ? null : stack.peek();
    }

    public static void removeThreadLogId() {
        Deque<String> stack = THREAD_LOG_ID_STACK.get();
        if (!stack.isEmpty()) {
            stack.pop();
        }
        if (stack.isEmpty()) {
            THREAD_LOG_ID_STACK.remove();
        }
    }
}
